import requests
from bs4 import BeautifulSoup as bs
import time
import urllib.request
import json


def read_data():
    url = "https://list.jd.com/index.html?cat=652,654,831"
    response = requests.get(url)
    if response.status_code == 200:
        cate_values = []
        b_obj = bs(response.text, 'html.parser')
        box_list = b_obj.select('li.gl-item')
        for box in box_list:
            i_list = box.select('div.p-img')
            for i in i_list:
                s_list = i.select('img')
                if len(s_list) == 0:
                    continue
                # s_name = s_list[0].text
                for s in s_list:
                    if s.has_attr('src'):
                        src = s.attrs['src']
                        print(src)
            d_list = box.select('div.p-name')
            for d in d_list:
                link_list = d.select('a')
                if len(link_list) == 0:
                    continue
                # second_name = link_list[0].text
                for link in link_list:
                    url = link.attrs['href']
                    print(url)
                    sku = url.split('/')[-1].strip(".html")
                    print(sku)
                    price_url = "https://p.3.cn/prices/mgets?skuIds=J_" + sku
                    response = urllib.request.urlopen(price_url)
                    content = response.read()
                    print(type(content))
                    result = json.loads(content)
                    record = result[0]
                    # print "price:", record['p']
                    print(record['p'])
                    return record['p']
            x_list = box.select('a')
            for x in x_list:
                xx_list = x.select('em')
                if len(xx_list) == 0:
                    continue
                xx1 = xx_list[0].text
                print(xx1)


def jd_price(url):
    sku = url.split('/')[-1].strip(".html")
    print(sku)
    price_url = "https://p.3.cn/prices/mgets?skuIds=J_" + sku
    response = urllib.request.urlopen(price_url)
    content = response.read()
    print(type(content))
    result = json.loads(content)
    print(result)
    record = result[0]
    # print "price:", record['p']
    return record['p']


if __name__ == '__main__':
    read_data()
    url = 'https://item.jd.com/12419422058.html'
    jd_price(url)
